{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pyspark,random"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "ls = [chr(random.randint(65,71)) \n",
    "     for i in range(1000)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "rdd = pyspark.SparkContext().parallelize(ls)\n",
    "rdd2 = rdd.map(lambda x :(x,random.randint(0,10000))).cache()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 传统模式计算平均数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[('B', 4762.109677419355),\n",
       " ('C', 5253.848),\n",
       " ('F', 4667.606666666667),\n",
       " ('A', 5231.463235294118),\n",
       " ('E', 4873.174825174825),\n",
       " ('G', 5127.118055555556),\n",
       " ('D', 5298.21768707483)]"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "rdd2.map(lambda x : (x[0],(x[1],1)))\\\n",
    ".reduceByKey(lambda x,y:(x[0]+y[0],x[1]+y[1]))\\\n",
    ".map(lambda x : (x[0],x[1][0]/x[1][1])).collect()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## groupByKey模式"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[('B', 4762.109677419355),\n",
       " ('C', 5253.848),\n",
       " ('F', 4667.606666666667),\n",
       " ('A', 5231.463235294118),\n",
       " ('E', 4873.174825174825),\n",
       " ('G', 5127.118055555556),\n",
       " ('D', 5298.21768707483)]"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "rdd2.groupByKey()\\\n",
    ".map(lambda x : (x[0],sum(x[1])/len(x[1])))\\\n",
    ".collect()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
